<?php

declare(strict_types=1);

namespace app\api\controller;

use app\api\lib\SuPengJun;
use app\api\service\CircleService;
use app\common\model\circle\CircleFansModel;
use app\common\model\circle\CircleModel;
use app\common\model\dynamic\DynamicModel;
use app\common\model\user\UserModel;
use think\facade\Db;
use think\Request;

class Circle extends Controller
{
    protected array $middleware = [
        'api' => ['except' => ['home', 'details']],
        'orCheck' => ['only' => ['home', 'details']]
    ];

    /**
     * 圈子首页推送列表
     */
    public function home(Request $request)
    {
        $todayTime = strtotime('today 00:00:00');
        $condition[] = ['status', '=', 1];
        $data = CircleModel::where($condition)
            ->field('id,name,avatar')
            ->order(['weigh' => 'desc', 'id' => 'desc'])
            ->select();
        $data->map(function ($v) use ($todayTime) {
            $v['dynamic_count'] = DynamicModel::where('circle_id', $v['id'])->where('create_time', '>', $todayTime)->count();
            $v['is_hot'] = $v['dynamic_count'] > 0;
            $v['user_count'] = CircleFansModel::where('circle_id', $v['id'])->where('create_time', '>', $todayTime)->count();
            $v['is_new'] = $v['user_count'] > 0;
        });
        return success('success', $data);
    }

    /**
     * 圈子列表（首页，我的）
     * @param array $type 类型:0=全部圈子,1=用户加入的圈子
     * @return json|array
     * @throws \AlibabaCloud|Client|Result|array
     */
    public function list(Request $request)
    {
        $uid = $request->uid;
        $type = $request->get('type', 0);
        $condition[] = ['status', 'in', [1, 2]];
        if ($type == 1) {
            $ids = CircleFansModel::where('user_id', $uid)->order(['id' => 'desc'])->column('circle_id');
            $ids_ordered = implode(',', $ids);
            if (count($ids)) {
                $condition[] = ['id', 'in', $ids];
                $data = CircleModel::where($condition)
                    ->orderRaw("FIELD(id, $ids_ordered)")
                    ->field(CircleService::circle_find())
                    ->paginate(12);
            } else {
                $data['data'] = [];
                return success('success', $data);
            }
        } else {
            $data = CircleModel::where($condition)
                ->field(CircleService::circle_find())
                ->order(['weigh' => 'desc', 'id' => 'desc'])
                ->paginate(12);
        }
        $data = CircleService::circle_map($data);
        return success('success', $data);
    }

    /**
     * 圈子详情
     */
    public function details(Request $request)
    {
        $uid = $request->uid;
        $id = $request->get('id');
        $condition[] = ['id', '=', $id];
        $condition[] = ['status', 'in', [1, 2]];
        $data = CircleModel::where($condition)->field('id,name,avatar,intro,browse,update_time')->find();
        if (!$data) return error('圈子状态异常或已被下架，请稍后重试！');
        if ($data['browse'] <= 0) {
            $data['browse'] = 1;
            CircleModel::where('id', $id)->update(['browse' => 1]);
        }
        $data['dynamic_count'] = DynamicModel::where('circle_id', $data['id'])->count();
        $data['user_count'] = CircleFansModel::where('circle_id', $data['id'])->count();
        if ($data['user_count'] > 0) {
            $uids = CircleFansModel::where('circle_id', $data['id'])->orderRaw('RAND()')->limit(3)->column('user_id');
            $data['user'] = UserModel::whereIn('id', $uids)->column('avatar');
        }
        $data['is_take'] = CircleFansModel::where('circle_id', $data['id'])->where('user_id', $uid)->value('id') > 0;
        $data['update_time_str'] = SuPengJun::timeStr($data['update_time']);
        CircleModel::where('id', $id)->update(['browse' => new \think\db\Raw('browse+1')]);
        return success('success', $data);
    }

    /**
     * 加入圈子
     */
    public function take(Request $request)
    {
        $uid = $request->uid;
        $id = $request->post('id', 0);
        $isTake = $request->post('is_take', false);
        CircleFansModel::where('user_id', $uid)->where('circle_id', $id)->delete();
        if ($isTake) {
            return success('已为您退出圈子！');
        } else {
            (new CircleFansModel)->insert(['user_id' => $uid, 'circle_id' => $id, 'create_time' => time()]);
            return success('已成功加入圈子 🎉🎉');
        }
    }

    /**
     * 获取用户加入的圈子
     */
    public function dynamic(Request $request)
    {
        $uid = $request->uid;
        $ids = CircleFansModel::where('user_id', $uid)->column('circle_id');
        $data = CircleModel::whereIn('id', $ids)->field('id,name,avatar')->select();
        return success('success', $data);
    }
}
